<?php

class Listing_Form_PostAnAddBoatForm extends Listing_Form_PostAnAddForm {

    private $_preview_link = '';
    private $_category;
    private $_adid;
    private $_listing;
    protected $elementButtonDecorators = array(
        'ViewHelper',
        'Errors',
    );
    protected $elementDecorators = array(
        'ViewHelper',
        'Errors',
    );
    protected $formDecorators = array(
        'PrepareElements',
        array('ViewScript', array('viewScript' => 'index/customization/boat-post-an-ad.phtml'))
    );
    protected $subFormDecorators = array(
        'FormElements',
        array('Description', array('placement' => 'prepend')),
        'fieldset',
    );
    protected $spanDecorators = array(
        'ViewHelper',
        'Errors',
        array('Label', array('placement' => 'prepend')),
        array(array('row' => 'HtmlTag'), array('tag' => 'span')),
    );
    protected $displayGroupDecorators = array(
        'FormElements',
        array('HtmlTag', array('tag' => 'p', 'class' => 'price radio text')),
        array('Description', array('placement' => 'prepend', 'tag' => 'label')),
    );
    protected $elementCheckBoxDecorators = array(
        'ViewHelper',
        'Errors',
        array('Label', array('placement' => 'APPEND')),
        array(array('row' => 'HtmlTag'), array('tag' => 'span')),
    );
    protected $elementMultiCheckBoxDecorators = array(
        'ViewHelper',
        'Errors',
    );
    protected $elementSelectDecorators = array(
        'ViewHelper',
        'Errors',
        array('Label', array()),
        array(array('row' => 'HtmlTag'), array('class' => 'select')),
    );
    protected $elementSelect2Decorators = array(
        'ViewHelper',
        'Errors',
        array('Label', array()),
    );
    protected $elementRadioDecorators = array(
        'ViewHelper',
        'Errors',
    );

    public function __construct($options = array()) {
        $this->_preview_link = !empty($options['preview_link']) ? $options['preview_link'] : '';
        $this->_category = !empty($options['category']) ? $options['category'] : array();
        $this->_adid = !empty($options['adid']) ? $options['adid'] : array();
        $this->_listing = !empty($options['listing']) ? $options['listing'] : new StdClass();
        parent::__construct();
    }

    public function init() {
        parent::init();
        $element = new Zend_Form_Element_Hidden('adid');
        $element->setValue((string) $this->_adid);
        $element->setDecorators(array(
            'ViewHelper'
                )
        );
        $this->addElement($element);

        $i = 0;
        foreach ($this->_category as $cat) {
            $i++;
            $element = new Zend_Form_Element_Hidden('category_link' . $i);
            $element->setValue((string) $cat->_id);
            $element->setDecorators(array(
                'ViewHelper'
                    )
            );
            $this->addElement($element);
        }
        $cat_str = '<ul>';
        foreach ($this->_category as $cat_id) {
            $cat_str .= '<li>';
            $tmp = array();
            $category = Model_Category::find($cat_id->_id);
            foreach ($category->getParentTree() as $cat) {
                $tmp[] = $cat->name;
            }
            $cat_str .= implode(' > ', $tmp);
            $cat_str .= '</li>';
        }
        $cat_str .= '</ul>';
        $this->setDescription($cat_str);

        //Title
        $this->addElement('text', 'tl_en', array(
            'validators' => array(
                array('NotEmpty', true, array('messages' => 'This information is required')),
            ),
            'decorators' => $this->elementDecorators,
            'required' => true,
        ));

        $this->addElement('hidden', 'add_more_checkbox', array(
            'filters' => array('StringTrim', 'StringToLower'),
            'validators' => array(
            ),
            'disableLoadDefaultDecorators' => true,
            'decorators' => array(
                'ViewHelper',
                'Errors',
                array(array('data' => 'HtmlTag'), array('style' => 'display:none')),
            ),
            'value' => 1,
            'required' => false,
        ));

        // Boat Type
        $boattype = Model_Listing_Boat::getBoatTypePostAd();
        if (empty($_POST['boattype'])) {
            $selected_boattype = 0;
            if (!empty($this->_listing)) {
                $selected_boattype = $this->_listing->boattype;
            }
        } else {
            $selected_boattype = $_POST['boattype'];
        }
        if (empty($selected_boattype)) {
            reset($boattype);
            $selected_boattype = key($boattype);
        }
        $this->addElement('select', 'boattype', array(
            //'filters'    => array('StringTrim'),
            'validators' => array(
                array('NotEmpty', true, array('messages' => 'This information is required')),
            ),
            'decorators' => array(
                'ViewHelper',
                'Errors',
                array('Label', array()),
            //array(array('row' => 'HtmlTag'), array('class'=>'select')),
            ),
            'multiOptions' => $boattype,
            'required' => true,
        ));

        // Boat Category
        $this->addElement('select', 'boatcategory', array(
            //'filters'    => array('StringTrim'),
            'validators' => array(
                array('NotEmpty', true, array('messages' => 'This information is required')),
            ),
            'decorators' => array(
                'ViewHelper',
                'Errors',
                array('Label', array()),
            //array(array('row' => 'HtmlTag'), array('class'=>'select')),
            ),
            'multiOptions' => Model_Listing_Boat::getBoatCategoryPostAd($selected_boattype),
            'required' => true,
        ));

        // Make
        $this->addElement('autoComplete', 'make', array(
            'jQueryParams' => array('source' => '/search/get-attribute?c=boats&f=model'),
            'validators' => array(
                array('NotEmpty', true, array('messages' => 'This information is required')),
            ),
            'decorators' => array(
                'Errors',
                'UiWidgetElement',
                array('Label', array('escape' => false)),
            //array(array('row' => 'HtmlTag'), array('tag' => 'p', 'class' => 'select')),
            ),
            'required' => true,
                )
        );

        // Year Manufactured
        $this->addElement('select', 'yearmanufactured', array(
            //'filters'    => array('StringTrim'),
            'validators' => array(
                array('NotEmpty', true, array('messages' => 'This information is required')),
            ),
            'decorators' => array(
                'ViewHelper',
                'Errors',
                array('Label', array()),
            //array(array('row' => 'HtmlTag'), array('class'=>'select')),
            ),
            'multiOptions' => Model_Listing_Car::getYearManufacturedPostAd(),
            'required' => true,
        ));

        // No of Previous Owners
        $this->addElement('select', 'previousowners', array(
            //'filters'    => array('StringTrim'),
            'validators' => array(
                array('NotEmpty', true, array('messages' => 'This information is required')),
            ),
            'decorators' => array(
                'ViewHelper',
                'Errors',
                array('Label', array()),
            //array(array('row' => 'HtmlTag'), array('class'=>'select')),
            ),
            'multiOptions' => Model_Listing_Car::getPreviousOwnersPostAd(),
            'required' => true,
        ));

        // Price
        $this->addElement('text', 'saleprice', array(
            'filters' => array('StringTrim', 'StringToLower'),
            'validators' => array(
                array('NotEmpty', true, array('messages' => 'This information is required')),
                array('Float', true, array('messages' => 'Numbers Only')),
            ),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementDecorators,
            'required' => true,
        ));

        // Dealer Name
        /* $this->addElement('text', 'dealername', array(
          //'filters'    => array('StringTrim', 'StringToLower'),
          'validators' => array(
          //'Int'
          ),
          'disableLoadDefaultDecorators' => true,
          'decorators' => $this->elementDecorators,
          'required'   => false,
          ));

          // Dealer Phone
          $this->addElement('text', 'dealerphone', array(
          //'filters'    => array('StringTrim', 'StringToLower'),
          'validators' => array(
          'Int'
          ),
          'disableLoadDefaultDecorators' => true,
          'decorators' => $this->elementDecorators,
          'required'   => false,
          ));

          // Dealer Email
          $this->addElement('text', 'dealeremail', array(
          //'filters'    => array('StringTrim', 'StringToLower'),
          'validators' => array(
          'EmailAddress',
          ),
          'disableLoadDefaultDecorators' => true,
          'decorators' => $this->elementDecorators,
          'required'   => false,
          )); */

        //Description
        $this->addElement('textarea', 'cs_en', array(
            //'filters'    => array('StringTrim'),
            'validators' => array(
                array('NotEmpty', true, array('messages' => 'This information is required')),
            ),
            'decorators' => $this->elementDecorators,
            'rows' => '',
            'required' => true,
            'label' => 'Description:',
        ));

        // Length
        $this->addElement('select', 'length', array(
            //'filters'    => array('StringTrim'),
            'validators' => array(
                array('NotEmpty', true, array('messages' => 'This information is required')),
            ),
            'decorators' => array(
                'ViewHelper',
                'Errors',
                array('Label', array()),
            //array(array('row' => 'HtmlTag'), array('class'=>'select')),
            ),
            'multiOptions' => Model_Listing_Boat::getLengthPostAd(),
            'required' => true,
        ));

        // Feature
        $this->addElement('select', 'feature', array(
            //'filters'    => array('StringTrim'),
            'validators' => array(
                array('NotEmpty', true, array('messages' => 'This information is required')),
            ),
            'decorators' => array(
                'ViewHelper',
                'Errors',
                array('Label', array()),
            //array(array('row' => 'HtmlTag'), array('class'=>'select')),
            ),
            'multiOptions' => Model_Listing_Boat::getFeaturePostAd(),
            'required' => true,
        ));

        // Engine Type
        $this->addElement('radio', 'enginetype', array(
            //'filters'    => array('StringTrim'),
            'validators' => array(
            //'EmailAddress',
            ),
            'decorators' => $this->elementRadioDecorators,
            'multiOptions' => Model_Listing_Boat::getEngineTypePostAd(),
            'required' => false,
        ));

        // Hull Material
        $this->addElement('radio', 'hullmaterial', array(
            //'filters'    => array('StringTrim'),
            'validators' => array(
            //'EmailAddress',
            ),
            'decorators' => $this->elementRadioDecorators,
            'multiOptions' => Model_Listing_Boat::getHullMaterialPostAd(),
            'required' => false,
        ));

        // Fuel Capacity
        $this->addElement('radio', 'fuelcapacity', array(
            //'filters'    => array('StringTrim'),
            'validators' => array(
            //'EmailAddress',
            ),
            'decorators' => $this->elementRadioDecorators,
            'multiOptions' => Model_Listing_Boat::getFuelCapacityPostAd(),
            'required' => false,
        ));

        // Trailer Included
        $this->addElement('select', 'trailerincluded', array(
            //'filters'    => array('StringTrim'),
            'validators' => array(
            //'EmailAddress',
            ),
            'decorators' => $this->elementSelect2Decorators,
            'multiOptions' => Model_Listing_Boat::getTrailerIncludedPostAd(),
            'required' => false,
        ));

        // Fuel Type
        $this->addElement('select', 'fueltype', array(
            //'filters'    => array('StringTrim'),
            'validators' => array(
            //'EmailAddress',
            ),
            'decorators' => $this->elementSelect2Decorators,
            'multiOptions' => Model_Listing_Boat::getFuelTypePostAd(),
            'required' => false,
        ));

        // Model Year
        $this->addElement('select', 'modelyear', array(
            //'filters'    => array('StringTrim'),
            'validators' => array(
            //'EmailAddress',
            ),
            'decorators' => $this->elementSelect2Decorators,
            'multiOptions' => Model_Listing_Boat::getModelYearPostAd(),
            'required' => false,
        ));

        $this->addElement('textarea', 'st_en', array(
            'filters' => array('StringTrim'),
            'validators' => array(
            ),
            'decorators' => $this->elementDecorators,
            'rows' => '',
            'required' => false,
        ));

        $areas = Model_Location::getAreaPostAd();
        if (empty($_POST['area_l1'])) {
            $selected_area = 0;
            if (!empty($this->_listing)) {
                $selected_area = $this->_listing->area_l1;
                if (empty($selected_area)) {
                    $loc = $this->_listing->district;
                    if (!empty($loc)) {
                        $selected_area = (string) $loc->getParent()->_id;
                    }
                }
            }
        } else {
            $selected_area = $_POST['area_l1'];
        }
        if (empty($selected_area)) {
            reset($areas);
            $selected_area = key($areas);
        }
        $this->addElement('select', 'area_l1', array(
            'filters' => array('StringTrim'),
            'validators' => array(
                array('NotEmpty', true, array('messages' => 'This information is required')),
            ),
            'multiOptions' => $areas,
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementDecorators,
            'required' => true,
        ));

        //District
        $this->addElement('select', 'district', array(
            'filters' => array('StringTrim'),
            'validators' => array(
                array('NotEmpty', true, array('messages' => 'This information is required')),
            ),
            'multiOptions' => Model_Location::getDistrictPostAd($selected_area),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementDecorators,
            'required' => false,
        ));
        $this->getElement('district')->setOptions(array('disabled' => 'disabled'));

        $this->addElement('button', 'validate', array(
            'required' => false,
            'ignore' => true,
            'type' => 'submit',
            'label' => 'Post your ad',
            'decorators' => array_merge($this->elementButtonDecorators, array(array(array('row' => 'HtmlTag'), array('tag' => 'p', 'class' => 'button_em')))),
        ));

        $this->addElement('button', 'preview', array(
            'required' => false,
            'ignore' => true,
            'type' => 'button',
            'label' => 'Preview',
            //'description' => '<a href="'.$this->_preview_link.'">Preview</a>',
            'decorators' => array_merge($this->elementButtonDecorators, array(array(array('row' => 'HtmlTag'), array('tag' => 'p', 'class' => 'preview button')))),
        ));


        $opt = $this->getDecorator('ViewScript')->getOptions();
        $opt['category'] = $this->_category;
        $opt['adid'] = $this->_adid;
        $opt['listing'] = $this->_listing;
        $opt['preview_link'] = $this->_preview_link;

        $this->getDecorator('ViewScript')->setOptions($opt);
    }

    public function populate(array $arr) {

        // Required
        //Title
        // if (empty($arr['title'])) {
        // $this->getElement('title')->setValue($this->_listing->title);
        // }
        //Description
        // if (empty($arr['description'])) {
        // $this->getElement('description')->setValue($this->_listing->description);
        // }

        if (Zend_Registry::get('current_language') == 'en') {
            $ft = 'en';
            $tt = 'zh-TW';

            $this->getElement('tl_en')->setValue($this->_listing->tl_en);
            $this->getElement('cs_en')->setValue($this->_listing->cs_en);
            $this->getElement('st_en')->setValue((string) $this->_listing->st_en);
        } else {
            $ft = 'zh-TW';
            $tt = 'en';

            $this->getElement('tl_en')->setValue($this->_listing->tl_tc);
            $this->getElement('cs_en')->setValue($this->_listing->cs_tc);
            $this->getElement('st_en')->setValue((string) $this->_listing->st_tc);
        }

        //Price
        if (empty($arr['saleprice'])) {
            $this->getElement('saleprice')->setValue($this->_listing->price);
        }
        //Make
        if (empty($arr['make'])) {
            $this->getElement('make')->setValue((string) $this->_listing->make);
        }
        //Boat Type
        if (empty($arr['boattype'])) {
            $this->getElement('boattype')->setValue((string) $this->_listing->boattype);
        }
        //Boat Category
        if (empty($arr['boatcategory'])) {
            $this->getElement('boatcategory')->setValue((string) $this->_listing->boatcategory);
        }
        //Year Manufactured
        if (empty($arr['yearmanufactured'])) {
            $this->getElement('yearmanufactured')->setValue((string) $this->_listing->yearmanufactured);
        }
        //Length
        if (empty($arr['length'])) {
            $this->getElement('length')->setValue((string) $this->_listing->length);
        }
        //Number of Previous Owner
        if (empty($arr['previousowners'])) {
            $this->getElement('previousowners')->setValue((string) $this->_listing->nopreviousowners);
        }
        //Feature
        if (empty($arr['feature'])) {
            $this->getElement('feature')->setValue((string) $this->_listing->feature);
        }
        //Area
        if (empty($arr['area_l1'])) {
            $selected_area = $this->_listing->area_l1;
            if (empty($selected_area)) {
                $loc = $this->_listing->district;
                if (!empty($loc)) {
                    $selected_area = (string) $loc->getParent()->_id;
                }
            }
            $this->getElement('area_l1')->setValue((string) $selected_area);
        }
        //District
        if (empty($arr['district'])) {
            if (isset($this->_listing->district->_id)) {
                $this->getElement('district')->setValue((string) $this->_listing->district->_id);
            }
        }
        //Street
        // if (empty($arr['street'])) {
        // $this->getElement('address')->setValue((string)$this->_listing->street);
        // }
        //Optional
        //Engine Type
        if (empty($arr['enginetype'])) {
            $this->getElement('enginetype')->setValue((string) $this->_listing->enginetype);
        }
        //Fuel Capacity
        if (empty($arr['fuelcapacity'])) {
            $this->getElement('fuelcapacity')->setValue((string) $this->_listing->fuelcapacity);
        }
        //Hull Material
        if (empty($arr['hullmaterial'])) {
            $this->getElement('hullmaterial')->setValue((string) $this->_listing->hullmaterial);
        }
        //Model Year
        if (empty($arr['modelyear'])) {
            $this->getElement('modelyear')->setValue((string) $this->_listing->modelyear);
        }
        //Fuel Type
        if (empty($arr['fueltype'])) {
            $this->getElement('fueltype')->setValue((string) $this->_listing->fueltype);
        }
        //Trailer Included
        if (empty($arr['trailerincluded'])) {
            $this->getElement('trailerincluded')->setValue((string) $this->_listing->trailerincluded);
        }

        parent::populate($arr);
        return $arr;
    }

    public function save($preview = false) {
        if (empty($this->_adid)) {
            $ad = new Model_Listing_Regular();
        } else {
            $ad = Model_Listing_Preview::find(new MongoId($this->_adid));
        }

        if (Zend_Registry::isRegistered('loggedin_user')) {
            $user = Zend_Registry::get('loggedin_user');
            if ($user->role == Model_User::ROLE_ADMIN) {
                if (empty($ad->us)) {
                    $ad->user = $user->_id;
                }
            } else {
                $ad->user = $user->_id;
            }
            if (empty($this->status)) {
                $ad->status = Model_Listing::STATUS_PUBLISHED;
            }
        } else {
            $ad->status = 6;
        }

        //Requiered Attributs
        // $ad->title          = $_POST['title'];
        // $ad->description    = $_POST['description'];

        $classname = Model_Listing::getInstanceClassname((array) $this->_listing->ca);
        $translateFields = $classname::getTranslationFormField();

        $this->translate($ad, $translateFields, $classname);

        //$ad->saleby         = $_POST['saleby'];
        //$ad->dealername     = $_POST['dealername'];
        //$ad->dealerphone    = $_POST['dealerphone'];
        //$ad->dealeremail    = $_POST['dealeremail'];
        $ad->nopreviousowners = $_POST['previousowners'];
        $ad->make = $_POST['make'];
        $ad->boattype = new MongoId($_POST['boattype']);
        $ad->boatcategory = new MongoId($_POST['boatcategory']);
        $ad->length = $_POST['length'];
        $ad->price = $_POST['saleprice'];
        $ad->yearmanufactured = $_POST['yearmanufactured'];
        $ad->feature = $_POST['feature'];
        //$ad->street                 = $_POST['address'];
        $ad->area_l1 = new MongoId($_POST['area_l1']);
        if ((string) $_POST['area_l1'] == ONLINE_ONLY_AREA) {
            $ad->district = new MongoId(ONLINE_ONLY_AREA);
        } else {
            $ad->district = new MongoId($_POST['district']);
        }

        //Optional Attributs
        if (!empty($_POST['enginetype'])) {
            $ad->enginetype = $_POST['enginetype'];
        }
        if (!empty($_POST['fuelcapacity'])) {
            $ad->fuelcapacity = $_POST['fuelcapacity'];
        }
        if (!empty($_POST['hullmaterial'])) {
            $ad->hullmaterial = $_POST['hullmaterial'];
        }
        if (!empty($_POST['modelyear'])) {
            $ad->modelyear = $_POST['modelyear'];
        }
        if (!empty($_POST['fueltype'])) {
            $ad->fueltype = $_POST['fueltype'];
        }
        if (!empty($_POST['trailerincluded'])) {
            $ad->trailerincluded = $_POST['trailerincluded'];
        }

        //Save the category related to this Ad
        foreach ($this->_category as $cat) {
            $ad->addCategory($cat->_id);
        }

        $this->continueFillup();
        if (!$preview) {
            $ad = Model_Listing_Preview::saveAsListing($ad);
            Model_Listing_Preview::remove(array('_id' => $ad->_id));
        } else {
            //$ad = Model_Listing_Preview::convertFromListing($ad);
            $ad->save();
        }
        return $ad;
    }

    protected function continueFillup() {
        
    }

    public function __toString() {
        $str = '
            $j("#boattype").change(function (event) {
                event.stopImmediatePropagation();
                $j.get("/search/get-attribute", { c:"boattype", f:"postad", id: $j("#boattype").val() },
                    function(data) {
                        $j("#boatcategory").empty();
                        $j.each(data, function (index, value) {
                            $(document.createElement("option"))
                                .html(value)
                                .attr("value", index)
                                .appendTo($("#boatcategory"));
                        });
                    });
           });
            $j("#area_l1").change(function (event) {
                event.stopImmediatePropagation();
                $j.get("/search/get-attribute", { c:"area_l1", f:"district_postad", id: $j("#area_l1").val() },
                    function(data) {
                        $j("#district").empty();
                        $j.each(data, function (index, value) {
                            $(document.createElement("option"))
                                .html(value)
                                .attr("value", index)
                                .appendTo($("#district"));
                        });
                        if ($j("#area_l1").attr("value") == "4cbe455a8835c17c10060000") {
                            $j("#district_div").hide();
                        }
                        else {
                            $j("#district_div").show();
                        }
                    });
           });

        ';

        $str2 = '
                $j("tl_tc_back").click(function(event) {
                alert("test");

                });

        ';
        $this->view->JQuery()->addJavascript($str);
        $this->view->JQuery()->addJavascript($str2);
        return parent::__toString();
    }

    public function isValid($post = array()) {
        $test1 = parent::isValid($post);
        $test2 = true;

        //Check Bad Words in Title
        if ($match = Ac_Util::checkBadWord($_POST['tl_en'])) {
            $this->getElement('tl_en')->addError('Your Ad contains banned words: ' . implode(', ', $match));
            $test2 = false;
        }

        //Check Bad Words in Description
        if ($match = Ac_Util::checkBadWord($_POST['cs_en'])) {
            $this->getElement('cs_en')->addError('Your Ad contains banned words: ' . implode(', ', $match));
            $test2 = false;
        }

        //Regex Title contain Email Address
        if (preg_match("#.[a-z0-9._-]+@[a-z0-9._-]{2,}\.[a-z]{2,4}.#", $_POST['tl_en'])) {
            $test2 = false;
        }
        //Regex description contain Email Address
        if (preg_match("#.[a-z0-9._-]+@[a-z0-9._-]{2,}\.[a-z]{2,4}.#", $_POST['cs_en'])) {
            $test2 = false;
        }

        // We need to check manually these fields
        else {
            /* if (empty($post['dealername'])) {
              $this->getElement('dealername')->addError('This information is required');
              $test2 = false;
              }
              if (empty($post['dealerphone'])) {
              $this->getElement('dealerphone')->addError('This information is required');
              $test2 = false;
              }
              if (empty($post['dealeremail'])) {
              $this->getElement('dealeremail')->addError('This information is required');
              $test2 = false;
              } */
        }

        //Exception for Online Only for Area and District
        $data = Model_Location::one(array('_id' => new MongoId($post['area_l1'])));
        if (!empty($data)) {
            if ($data->nm_en != 'Online Only') {
                if (empty($post['district'])) {
                    $this->getElement('district')->addError('This information is required');
                    $test2 = false;
                }
            }
        }

        //Check the two validations
        if ($test1 & $test2) {
            return true;
        } else {
            return false;
        }
    }

}
